import 'package:flutter/material.dart';

import '../../../controller/FormController.dart';
import '../../../store/template/template.dart';

class TemplateFormController extends FormController {
  TemplateData formData = TemplateData();

  setFormData(TemplateData data) {
    formData = data;
  }

  setFormItemValue(String name, data) {
    formData.name = data;
  }

  TemplateData getFormData() {
    return formData;
  }
}

class TemplateForm extends StatefulWidget {
  final TemplateFormController controller;
  const TemplateForm({super.key, required this.controller});

  @override
  State<TemplateForm> createState() => _TemplateFormState();
}

class _TemplateFormState extends State<TemplateForm> {
  setData(Map<String, String>? data) {
    if (data == null) {
      return;
    }
    setState(() {
      // name = data['name']!;
      // name = data['path']!;
      // name = data['desc']!;
    });
  }

  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      widget.controller.initFormState(_formKey);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(0),
      child: Form(
        key: _formKey,
        child: ListView(
          children: renderChildren,
        ),
      ),
    );
  }

  List<Widget> get renderChildren {
    return [
      Expanded(
        child: Column(
            children: insertBetween(
                [
              renderTemplateName(),
              renderTemplatePath(),
              renderTemplateDesc(),
              renderTemplateValueListItem()
            ],
                const SizedBox(
                  height: 20,
                ))),
      )
    ];
  }

  // 绘制name字输入框
  TextFormField renderTemplateName() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '模板名称',
        hintText: '请输入模板名称',
      ),
      onChanged: (value) => setState(() {
        widget.controller.getFormData().name = value;
      }),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入模板名称';
        }
        return null;
      },
    );
  }

  //  值列表
  renderTemplateValueListItem() {
    Widget addButton = ElevatedButton(
      child: const Text('添加'),
      onPressed: () {
        setState(() {
          if (widget.controller.getFormData().valueListItem == null) {
            widget.controller.getFormData().valueListItem = [];
          }
          widget.controller.getFormData().valueListItem!.add(ValueListItem());
        });
      },
    );

    Widget removeButton = ElevatedButton(
      child: Text('删除'),
      onPressed: () {
        setState(() {
          // widget.controller.getFormData().valueListItem!.removeLast();
          widget.controller.getFormData().valueListItem!.removeLast();
        });
      },
    );

    Widget renderItem() {
      return Column(
        children: widget.controller.getFormData().valueListItem != null
            ? widget.controller.getFormData().valueListItem!.map((item) {
                return Row(
                  children: [Text('name'), Text('type'), removeButton],
                );
              }).toList()
            : [],
      );
    }

    return Column(
      children: widget.controller.getFormData().valueListItem != null
          ? [renderItem(), addButton]
          : [addButton],
    );
  }

  // 绘制path输入框
  TextFormField renderTemplatePath() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '模板路径',
        hintText: '请输入模板路径',
      ),
      onChanged: (value) => setState(() {
        widget.controller.getFormData().desc = value;
      }),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入模板路径';
        }
        return null;
      },
    );
  }

  // 绘制desc输入框
  TextFormField renderTemplateDesc() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '模板描述',
        hintText: '请输入模板描述',
      ),
      onChanged: (value) => setState(() {
        widget.controller.getFormData().desc = value;
      }),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入模板描述';
        }
        return null;
      },
    );
  }
}

List<T> insertBetween<T>(List<T> list, T element) {
  List<T> result = [];

  for (int i = 0; i < list.length; i++) {
    result.add(list[i]);
    if (i != list.length - 1) {
      result.add(element);
    }
  }

  return result;
}
